package com.example.servlettemplate.servlet;

import com.example.servlettemplate.dao.UserDAO;
import com.example.servlettemplate.pojo.User;
import com.example.servlettemplate.util.RequestUtil;
import com.example.servlettemplate.util.SystemConstants;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    //验证用户名是否已经注册
    private UserDAO userDAO = new UserDAO();
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = RequestUtil.getString(req, "username");
        if(username == null){
            error("用户名不能为空", req, resp);
            return;
        }
        String nickname = RequestUtil.getString(req, "nickname");
        if(nickname == null){
            error("昵称不能为空", req, resp);
            return;
        }
        String password = RequestUtil.getString(req, "password");
        if(password == null){
            error("密码不能为空", req, resp);
            return;
        }
        String repeatPassword = RequestUtil.getString(req, "repeatPassword");
        if(repeatPassword == null){
            error("确认密码不能为空", req, resp);
            return;
        }
        if(!repeatPassword.equals(password)){
            error("两次密码不一致", req, resp);
            return;
        }


        //查询数据库里面的用户
        User user = userDAO.getUserByUsername(username);
        if(user != null){
            error("用户名已存在", req, resp);
            return;
        }
        //添加用户
        user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        int result = userDAO.add(user);
        if(result == 1){
            //成功后跳转到登陆页面
            req.getRequestDispatcher(SystemConstants.PAGE_PATH + "login.jsp").forward(req, resp);//请求转发跳转页面
        }else {
            error("修改失败，请稍后再试", req, resp);
        }
    }

    public void error(String message, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setAttribute("message", message);//动态错误信息message
        req.getRequestDispatcher(SystemConstants.PAGE_PATH + "register.jsp").forward(req, resp);//请求转发跳转页面
        return;
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
